# coding:utf-8

from PIL import Image, ImageFont, ImageDraw
import random
import base64
import io


class Captcha(object):
    def __init__(self, size=(100, 38), font_size=30):
        self.font = ImageFont.truetype("simsun.ttf", font_size)
        self.size = size
        self.image = Image.new("RGBA", self.size, (255,) * 4)
        self.texts = self.random_text(5)

    @staticmethod
    def random_text(length):
        all_chars = "123456789abcdefghijkmnpqrstuvwxyz"
        return "".join(all_chars[random.randint(0, len(all_chars) - 1)] for i in range(length))

    @staticmethod
    def random_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    def write(self, text, x):
        draw = ImageDraw.Draw(self.image)
        draw.text((x, 4), text, fill=self.random_color(), font=self.font)

    def rotate(self):
        rot = self.image.rotate(random.randint(-10, 10), expand=0)
        fff = Image.new("RGBA", rot.size, (255,) * 4)
        self.image = Image.composite(rot, fff, rot)

    def write_codes(self):
        x = 10
        xplus = 15

        for text in self.texts:
            self.write(text, x)
            self.rotate()
            x += xplus

        return self.texts

    def base64(self):
        self.write_codes()
        buffer = io.BytesIO()
        self.image.save(buffer, format="JPEG")
        buffer.seek(0)
        return base64.b64encode(buffer.getvalue()).decode("utf-8")

    def save(self, name):
        self.write_codes()
        self.image.save(name)
